import {
  requestCloud,
  saveDevProperty,
  getLaunchOptionsSync,
  getDevProperty,
  getDeviceProperty,
} from '@ray-js/ray';
import { devices } from '@/devices';

const launchOption = getLaunchOptionsSync();
const deviceId = launchOption?.query?.deviceId;

const errStyle = 'background: red; color: #fff;';

export function api(url: string, postData: any, version = '1.0') {
  return new Promise((resolve, reject) => {
    requestCloud({
      api: url,
      data: postData,
      version,
      success(data) {
        try {
          const res = typeof data === 'string' ? JSON.parse(data) : data;
          resolve(res);
        } catch (e) {
          console.log(`API 请求失败: %c${url}%o`, errStyle, data);
          resolve(data);
        }
      },
      fail({ errorMsg }) {
        try {
          const e = typeof errorMsg === 'string' ? JSON.parse(errorMsg) : errorMsg;
          reject(e);
        } catch (err) {
          console.log(`API 请求失败: 参数：`, postData);
          console.log(`API 请求失败: %c${url}%o`, errStyle, errorMsg);
          reject(errorMsg);
        }
      },
    });
  });
}

export const saveCloudData = ({ code, value }) => {
  console.log(`🚀 saveCloudData`, {
    [code]: value,
  })


  return devices.lamp.model.abilities.storage?.set(code, value);
};



export const getCloudData = () => {
  return new Promise((resolve, reject) => {
    getDeviceProperty({
      deviceId,
      success: info => {
        console.log('getDeviceProperty success', info);
        resolve(info.properties);
      },
      fail: error => {
        console.log('getDeviceProperty fail', error);
        reject({});
      },
    });
  });

  // return getDevProperty({
  //   devId: deviceId,
  //   bizType: 0,
  //   code: 'clock_name2',
  //   // propertyList: JSON.stringify([]),
  // })
  //   .then(response => {
  //     console.log(response);
  //   })
  //   .catch();
};
